package com.qf.usermybatis.controller;

import com.github.pagehelper.PageInfo;
import com.qf.usermybatis.entity.User;
import com.qf.usermybatis.service.UserService;
import com.qf.usermybatis.service.impl.UserServiceImpl;

import java.io.*;
import java.util.Objects;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

@WebServlet("/users")
public class UserServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 设置响应编码
        response.setContentType("text/html;charset=utf-8");
        try {
            // 获取传递的参数,查询第几页/每页几条数据
            String pageNum = request.getParameter("pageNum");
            String pageSize = request.getParameter("pageSize");
            if (Objects.isNull(pageNum) || "".equals(pageNum)) {
                pageNum = "1";
            }
            if (Objects.isNull(pageSize) || "".equals(pageSize)) {
                pageSize = "5";
            }
            // 调用业务层的方法
            PageInfo<User> pageInfo = userService.selectAll(Integer.valueOf(pageNum), Integer.valueOf(pageSize));
            // 把查询到的数据添加到request域中
            request.setAttribute("pageInfo", pageInfo);
            // 转发到index页面显示数据
            request.getRequestDispatcher("index.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

}